# -*- codeing = utf-8 -*-
# @Time : 2021/3/20 0020 9:48
# @Author : Alan Franklin
# @File : UI_functions.py
# @Software: PyCharm
from tkinter import *
from tkinter import filedialog
from tkinter.messagebox import *
from UI_globalstack import *
from UI_checkdetails import *
import os


class FunctionInterface(object):
    def __init__(self, master=None):
        self.root = master
        self.root.geometry('720x480')
        self.varhistory = StringVar()
        self.varselect = StringVar()
        self.CreatePage()

    def CreatePage(self):
        self.detectionpage = Frame(self.root)
        self.historypage = Frame(self.root)
        self.detectionpage.pack()

        menubar = Menu(self.root)
        menubar.add_command(label='图片检测', command=self.ImageDetection)
        menubar.add_command(label='历史记录', command=self.HistoryCheck)
        self.root['menu'] = menubar

        Button(self.detectionpage, text='选择图片', height=2, command=self.SelectImage).pack()

        Button(self.historypage, text='查看详情', height=2, command=self.Check).pack()
        self.lb = Listbox(self.historypage, listvariable=self.varhistory)
        self.lb.pack()

    def ImageDetection(self):
        self.detectionpage.pack()
        self.historypage.pack_forget()

    def HistoryCheck(self):
        self.detectionpage.pack_forget()
        self.historypage.pack()
        self.varhistory.set(self.ReadFromRuns())

    def SelectImage(self):
        conven = 'python detect.py --weights best.pt --source '
        savetxt = ' --save-txt'
        #route = 'images/tesouracurva552.jpg'
        route = filedialog.askopenfilename()
        os.system(conven + route + savetxt)
        #showinfo(title='提示', message='检测成功！')
        label_dir = self.ReadFromRuns()
        self.varselect.set(label_dir[len(label_dir)-1])
        self.detectionpage.destroy()
        self.historypage.destroy()
        gs.mystack.Push(self)
        DetailsInterface(self.root, self.varselect)

    def ReadFromRuns(self):
        # 暂时规定，每次检测一张图片
        label_dir = []
        get_dir = os.listdir(r'runs\detect')
        for i in get_dir:
            exp_dir = os.path.join(r'runs\detect', i)
            label_dir.append(exp_dir)
        return label_dir

    def Check(self):
        value = self.lb.get(self.lb.curselection())
        self.varselect.set(value)
        self.detectionpage.destroy()
        self.historypage.destroy()
        gs.mystack.Push(self)
        DetailsInterface(self.root, self.varselect)
